package com.example.qxfw.nyqx.service.impl;

import com.example.qxfw.common.entity.zy.AgriProduct;
import com.example.qxfw.mongodb.hy.entity.HyImageFile;
import com.example.qxfw.mongodb.hy.service.HyImageFileService;
import com.example.qxfw.nyqx.service.AgriProductService;
import com.example.qxfw.nyqx.service.NyqhService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class NyqhServiceImpl implements NyqhService {


    @Autowired
    private AgriProductService agriProductService;

    @Autowired
    private HyImageFileService imageFileService;

    @Override
    public byte[] getQuhuatu(String qhClassName,String qhType) {
        qhClassName = qhClassName+".jpg";
        List<AgriProduct> agriProducts = agriProductService.listByParam2(qhClassName, qhType);
        if (agriProducts.size()==0){
            return null;
        }
        String tableId = String.valueOf(agriProducts.get(0).getId());
        HyImageFile imageFile = imageFileService.getByParam(tableId, "agri_product");
        if (imageFile==null||imageFile.getName()==null){
            return null;
        }
        return imageFile.getData();
    }

    @Override
    public HyImageFile saveQhImage(MultipartFile qhImage, String qhClassName, String qhType) throws IOException {
        qhClassName = qhClassName + ".jpg";
        List<AgriProduct> agriProducts = agriProductService.listByParam2(qhClassName, qhType);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        AgriProduct newAgriProduct;
        if (agriProducts.size()==0){
            AgriProduct agriProduct= new AgriProduct();
            agriProduct.setProductname(qhClassName);
            agriProduct.setProducttype(qhType);
            agriProduct.setForecasttime(new Date());
            agriProduct.setMaketime(new Date());
            agriProduct.setMaker("admin");
            newAgriProduct = agriProductService.saveProduct(agriProduct);
        } else {
            newAgriProduct = agriProducts.get(0);
            newAgriProduct.setMaketime(new Date());
            agriProductService.update(newAgriProduct);
        }

        HyImageFile hyImageFile = new HyImageFile();
        hyImageFile.setId(String.valueOf(newAgriProduct.getId()));
        hyImageFile.setTable_name("agri_product");
        hyImageFile.setData(qhImage.getBytes());
        hyImageFile.setName("测试图片");

        return imageFileService.save(hyImageFile);
    }
}
